#include "ui_mainwindow.h"
#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    var_udpClient = new udpClient(this);

    if(var_udpClient->isSuccessfullyOpen())
    {
        initTableView();
        show();

        connect(ui->node_tableView,&QTableView::customContextMenuRequested,this,&MainWindow::popUpContextMenu);
        connect(ui->searchNode_button,&QPushButton::clicked,var_udpClient,&udpClient::sendCommand);
        connect(ui->searchNode_button,&QPushButton::clicked,this,[&]{ui->statusbar->showMessage("");});
        connect(var_udpClient,&udpClient::getIpAndName,this,&MainWindow::updateServerInformation);
        connect(ui->searchNode_button,&QPushButton::clicked,this,&MainWindow::updateServerInformation);
        connect(var_udpClient,&udpClient::textLabel,this,&MainWindow::displayTextLabel);
    }
    else
    {
        show();
        QMessageBox::warning(this,tr("警告"),tr("端口已被占用!\n请检查客户端是否已开启!"));
    }
}

MainWindow::~MainWindow()
{
    qDebug() << "mainwindow 析构";
    delete ui;
}

void MainWindow::initTableView()
{
    var_itemModel = new QStandardItemModel(this);
    var_itemModel->setHorizontalHeaderLabels({"IP Adress","Port Number","  Host Name  "});

    var_delegate = new CenteredDelegate(ui->node_tableView); // 创建一个委托
    ui->node_tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->node_tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->node_tableView->setModel(var_itemModel);
    ui->node_tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->node_tableView->verticalHeader()->setHidden(true);
    ui->node_tableView->setItemDelegate(var_delegate); // 通过委托设置格式
}

void MainWindow::updateServerInformation()
{
    qDebug("update.........");
    var_itemModel->removeRows(0,var_itemModel->rowCount());
    QString ipAddress, hostName;
    for(auto &stringlist : IpAndHostName)
    {
        QList<QStandardItem*>item;
        ipAddress = stringlist.at(0);
        hostName = stringlist.at(1);
        item.append(new QStandardItem(ipAddress));
        item.append(new QStandardItem(QString::number(TCP_SERVER_PORT)));
        item.append(new QStandardItem(hostName));
        var_itemModel->appendRow(item);
    }
}

void MainWindow::popUpContextMenu(const QPoint &pos)
{
    if(!ui->node_tableView->indexAt(pos).isValid())
        return;

    int row = ui->node_tableView->indexAt(pos).row();
    ui->node_tableView->selectRow(row); //解决摁住鼠标再松开不显示鼠标所指row的问题

    QMenu contextMenu;
    QAction *connectAction = contextMenu.addAction("连接");
    QAction *cancelAction = contextMenu.addAction("取消");
    QAction *selectedAction = contextMenu.exec(ui->node_tableView->viewport()->mapToGlobal(pos));
    if(selectedAction == connectAction)
    {
        QString ip = var_itemModel->item(row,0)->text(); // IP Address
        QString name = var_itemModel->item(row,2)->text(); // Host name
        qDebug() << "Ip:" << ip;
        qDebug() << "Name:" << name;
        if(Map_AvoidReopenWidgets.contains(ip))
        {
            QMessageBox msg(QMessageBox::Information,"提示","该IP下的节点控制台已打开");
            msg.addButton(QMessageBox::Ok);
            msg.exec();
        }
        else
        {
            Map_AvoidReopenWidgets.insert(ip,name);

            MyWidget *widget = new MyWidget(nullptr,ip,name);
            widget->setAttribute(Qt::WA_DeleteOnClose); // 关闭窗口自动删除
            connect(widget,&MyWidget::textLabel,this,&MainWindow::displayTextLabel);
        }
    }
    else if(selectedAction == cancelAction)
    {
        qDebug("close!!");
    }
}
void MainWindow::displayTextLabel(QString text)
{
    if(text == tr("服务器连接中....."))
    {
        qDebug() << text;
        setEnabled(false);
    }
    else
    {
        setEnabled(true);
    }
    ui->statusbar->showMessage(" "+text);
}


